package com.smart.framework.util;

/**
 * <p><b>Description:</b>  TODO
 * <p><b>Company:</b>
 *
 * @author created by Jesse Xu at 14:29 on 2019/11/20
 * @version V0.1
 * @classNmae Queue
 */
public class CircularQueue {

    private int capacity = 0;

    private String[] items ;

    private int head = 0;

    private int tail = 0;

    private int size = 0;

    public CircularQueue(int capacity){
        items = new String[capacity];
        this.capacity = capacity;
    }

    /**
     * dequeue
     * @return String
     */
    public String dequeue(){
        //判断队列是否为空
        if(size==0){
            return null;
        }
        String item = items[head];
        //队列到队尾了，需要重新将队tail 置数组首部
        head = (head + 1) % capacity;
        size--;
        return item;
    }

    /**
     *
     * @param item
     * @return
     */
    public boolean enqueue(String item){
        //判断队列是否已满
        if(size == capacity){
            return false;
        }
        //队列到队尾了，需要重新将队tail 置数组首部

        items[tail] = item;
        tail = (tail + 1) % capacity;
        size++;
        return true;
    }

    public void print(){
        if(tail == head){
            System.out.println("empty queue");
        }
        int index = head;
        StringBuilder sb = new StringBuilder();
        do{
            sb.append(items[index]+"->");
            index = (index + 1) % capacity;
        }while (index != tail);
        System.out.println(sb.subSequence(0,sb.lastIndexOf("->")));
    }

    public static void main(String[] args) throws InterruptedException {
        CircularQueue queue = new CircularQueue(10);

       Thread th1= new Thread(()->{
            queue.enqueue("A");
            queue.enqueue("B");
            queue.enqueue("C");
            queue.enqueue("D");
            queue.enqueue("E");
        });
        Thread th2 = new Thread(()->{
            queue.enqueue("F");
            queue.enqueue("G");
            queue.enqueue("H");
            queue.enqueue("I");
            queue.enqueue("J");
        });
        th2.start();
        th1.start();

        Thread.sleep(1000);
        queue.print();
    }

}
